package xyz.robinbingo.pfboot.web.controller;

import cn.hutool.core.util.StrUtil;
import org.omnifaces.util.Faces;
import org.springframework.beans.factory.annotation.Autowired;
import xyz.robinbingo.pfboot.entity.Car;
import xyz.robinbingo.pfboot.repository.CarRepository;
import xyz.robinbingo.pfboot.util.FaceUtils;

import javax.annotation.PostConstruct;
import javax.faces.view.ViewScoped;
import javax.inject.Named;
import java.io.IOException;

/**
 * CarFormController
 *
 * @author Robin
 * @date 2018/10/19 17:24
 **/
@Named
@ViewScoped
public class CarFormController {

    @Autowired
    private CarRepository carRepository;

    private static final String CAR_LIST_URL = "car/car-list.xhtml";

    private Integer id;
    private Car car;

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public Car getCar() {
        return car;
    }

    public void setCar(Car car) {
        this.car = car;
    }

    @PostConstruct
    public void init() {
        String param = FaceUtils.getParam("id");
        if (StrUtil.isNotBlank(param)) {
            id = Integer.valueOf(param);
            car = carRepository.findById(id).orElse(null);
        } else {
            car = new Car();
        }
    }

    /**
     * 删除车辆
     *
     * @author Robin
     * @date 2018/10/22 10:22
     **/
    public void delete() throws IOException {
        if (car != null && car.getId() != null) {
            carRepository.delete(car);
            FaceUtils.addMessage("成功删除车辆：" + car.getName());
            Faces.getFlash().setKeepMessages(true);
            Faces.redirect(CAR_LIST_URL);
        }
    }

    /**
     * 保存车辆
     *
     * @author Robin
     * @date 2018/10/22 10:22
     **/
    public void save() throws IOException {
        carRepository.save(car);
        FaceUtils.addMessage("车辆：" + car.getName() + "保存成功！");
        Faces.getFlash().setKeepMessages(true);
        Faces.redirect(CAR_LIST_URL);
    }

    /**
     * 清空表单内容
     *
     * @author Robin
     * @date 2018/10/22 10:23
     **/
    public void clear() {
        car = new Car();
        id = null;
    }

    /**
     * 判断是否为新建车辆
     *
     * @author Robin
     * @date 2018/10/22 10:23
     **/
    public boolean isNew() {
        return car == null || car.getId() == null;
    }
}
